#include "cloud_opt_handler.h"
#include "cJSON.h"
#include "file_opt.h"

#define SAVE_FILE_PATH "log.txt"

int main(int argc, char const *argv[])
{
    char url_str[256], post_str[256];

    if(argc != 3){
        printf("usage: %s <url> <post_str>\n", argv[0]);
        strcpy(url_str, "www.kuaidi100.com/query");
        strcpy(post_str, "type=shentong&postid=3391187608584");
    }else{
        strcpy(url_str, argv[1]);
        strcpy(post_str, argv[2]);
    }

    //这4句整个进程初始化一次
    struct handle_obj *default_handle;
    CloudOpt_init();
    CloudOpt_Show();
    default_handle = CloudOpt_GetHandle("curl");

    //结果写入字符串
    char ret_buf[2048] = {0};
    default_handle->init(url_str);
    default_handle->post2str(post_str, ret_buf);
    default_handle->release();

    printf("origin result = %s\n", ret_buf);

    printf("-----------------parse json----------------------------\n");


    //结果写入文件
    default_handle->init(url_str);
    default_handle->post2file(post_str, SAVE_FILE_PATH);
    default_handle->release();

    int filesize = FileOpt_GetSize(SAVE_FILE_PATH);
    char *read_buf = (char *)malloc(filesize);
    if(read_buf == NULL){
        return -1;
    }
    memset(read_buf, 0, filesize);
    FileOpt_ReadAll(SAVE_FILE_PATH, read_buf);
//    printf("read buf = %s\n", read_buf);

    //json解析，这只是个参考例子
    cJSON * root = NULL;
    cJSON * item = NULL;

    root = cJSON_Parse(read_buf);
    if(NULL == root){
        printf("parse err, check json_str\n");
        return -1;
    }

    char *nu_str = cJSON_GetObjectItem(root, "nu")->valuestring;
    printf("root num = %s\n", nu_str);

    item = cJSON_GetObjectItem(root, "data");  //获取到data数组域
    cJSON *data_list = item->child;  //指向第一个数组项
    while (NULL != data_list) {
        printf("data context = %s\n", cJSON_GetObjectItem(data_list, "context")->valuestring);
        data_list = data_list->next;
    }

    printf("\ndata is save to %s\n", SAVE_FILE_PATH);

    return 0;
}
